package com.fredia.terp.util;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import javax.servlet.http.HttpServletRequest;

/**
 * 对 spring ServletRequestUtils 的一个简单继承，使用该类可以方便的获取参数。<br />
 * 灵活使用和扩展。
 * 
 * @author : wangyong
 * @since : 2017年6月27日
 * @version : v0.0.1
 */
public class ServletUtils extends ServletRequestUtils {

	/**
	 * 页面以“,”拼写的字符串，传递到后台以后分割为数字数组形式。
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static int[] getIntParameters(HttpServletRequest request, String name) {
		String agrs = request.getParameter(name);
		if (StringUtils.hasText(agrs)) {
			String[] as = agrs.split(",");
			int[] rs = new int[as.length];
			for (int i = 0; i < as.length; i++) {
				int z = 0;
				try {
					z = Integer.valueOf(as[i]);
				} catch (NumberFormatException e) {
					continue;
				}
				rs[i] = z;
			}
			return rs;
		} else {
			return new int[] {};
		}
	}

	/**
	 * 使用 Long 默认值的获取参数。
	 * 
	 * @author 王帅 @
	 * @param request
	 * @param name
	 * @param defaultValue
	 * @return
	 */
	public static Long getLongParameter(HttpServletRequest request, String name, Long defaultValue) {
		String agrs = request.getParameter(name);
		try {
			defaultValue = Long.parseLong(agrs);
		} catch (NumberFormatException e) {
		}
		return defaultValue;
	}

	public static Integer getIntParameter(HttpServletRequest request, String name, Integer defaultValue) {
		String agrs = request.getParameter(name);
		try {
			defaultValue = Integer.parseInt(agrs);
		} catch (NumberFormatException e) {
		}
		return defaultValue;
	}

	/**
	 * 获取客户外网id
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (ip != null && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (ip != null && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		} else {
			return request.getRemoteAddr();
		}
	}

}
